import axios from 'axios'
import { Message } from 'element-ui'
const env = process.env.NODE_ENV

const instance = axios.create({
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded', // POST请求的Content-Type
  },
  transformRequest: [
    (data, headers) => {
      if (data instanceof FormData || !data) return data

      if (headers['Content-Type'] === 'application/json') return JSON.stringify(data)

      const query = []

      Object.keys(data).forEach(item => {
        // encodeURIComponent window对象的全局方法，对中文及特殊字符进行编码
        query.push(`${encodeURIComponent(item)}=${encodeURIComponent(data[item])}`)
      })

      return query.join('&')
    },
  ],

  timeout: 10 * 60 * 1000,
})

//请求拦截器
instance.interceptors.request.use(request => {
  // 设置公共请求headers
  const token = localStorage.getItem('token')
  const { config } = request

  // let baseURL = 'development' === env ? 'http://localhost:8080' : 'http://orgin.club'
  // if (url.indexOf('http') === 0) request.baseURL = ''
  // else request.baseURL = baseURL

  // 是否需要发送token
  let { sendToken } = config || {}
  sendToken = typeof sendToken === 'boolean' ? sendToken : true
  if (sendToken && token) request.headers.token = token

  return request
})

// 响应拦截器
instance.interceptors.response.use(
  ({ config, data: res }) => {
    const { code, message } = res
    let { showErrorMsg } = config || {}

    if (typeof showErrorMsg !== 'boolean') showErrorMsg = true

    if (code == 0) return res

    if (code == 10000) {
      const { location } = window
      const herf = `${location.origin}/#/login` // token失效
      localStorage.clear()
      sessionStorage.clear()
      location.replace(herf)
    } else if (showErrorMsg) Message({ message, type: 'error' })

    return res
  },
  e => {
    const error = e.toJSON()
    let { showErrorMsg } = error.config || {}
    if (typeof showErrorMsg !== 'boolean') showErrorMsg = true
    console.log(error)
    if (showErrorMsg) Message({ message: error.message, type: 'error' })
    return Promise.resolve(error)
  },
)

export default instance
